package tcp;

/**
 * Created by lizhun on 16/6/15.
 */

import com.nativetalk.base.RetInfo;
import com.nativetalk.common.util.BeanToJson;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.log4j.Logger;

import java.util.concurrent.ConcurrentHashMap;

public class HelloServerHandler extends SimpleChannelInboundHandler<String> {
    private static final Logger logger = Logger.getLogger(HelloServerHandler.class.getName());
    private static Long  markId = 0L;
    private long id = 0;
    public static ConcurrentHashMap<String, Channel> clientChannelMap = new ConcurrentHashMap<String, Channel>();
    private ClientTask task;
    public HelloServerHandler(){
        synchronized (markId){
            this.id = ++markId;
        }
    }
    // 1
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info(this.toString());
        task = new ClientTask(ctx.channel());
        ctx.fireChannelRegistered();
    }
    // 2
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info(this.toString());
        super.channelActive(ctx);
        RetInfo retInfo = new RetInfo();
        retInfo.setMark("200");
        retInfo.setTip("连接成功");
        String result = BeanToJson.RetInfoToJson(retInfo);
        ctx.writeAndFlush(result);
    }
    // 3
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String params) {
        logger.info(this.toString());
        if (ctx.channel().isOpen()) {
            task.acceptRequest(params, clientChannelMap);
        }
    }
    // 4
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        logger.info(this.toString());
        ctx.fireChannelReadComplete();
    }
    // - 5
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info(this.toString());
        ctx.fireChannelActive();
    }
    // - 6
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        logger.info(this.toString());
    }
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        logger.info(this.toString());
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.info(this.toString());
        logger.error(cause.getMessage() + " Handler Instance:" + this.toString(), cause);
        ctx.close();
    }

    @Override
    public String toString() {
        return super.toString()+"{" +
                "id=" + id +
                ", task=" + task +
                '}';
    }
}
